<template>
  <el-dialog
    v-dialogDrag
    :visible="popupsVisible"
    width="70%"
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="closeEdit"
    @open="open"
  >
    <dialogHeader
      slot="title"
      :title="titleName"
      :style-type="$store.state.app.dialogType"
    />
    <!-- 显示按钮的onetabel -->
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-table-defult-height="350"
      :dynamic-is-show-more-btn="false"
      :callback-obj="callbackObj"
    />
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import { orgApis } from '@/api/paSparePartsManagement'
import api from "@/views/pa/financialManagement/sparePartsBonusOperation/api";

// import { orgApis } from '@/api/vesalesapi.js'
export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  props: {
    editRowData: Object,
    popupsState: String,
    popupsVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      uploadPath: '',
      upLoadList: [],
      watchList: [],
      tableCols: [],
      selectiondata: [],
      editPopupsVisible: false,
      titleName: '索赔申请单制作',
      // 网格查询API配置对象
      apiConfig: orgApis.purchaseApplicationClaimMakeQuery,
      // 动态组件-按钮
      tableButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              icon: 'iconfont  icon-preservation',
              clickEvent: () => this.TemporaryStorage(),
              text: '暂存'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              icon: 'iconfont icon-preservatio',
              clickEvent: () => this.saveAndCommit(),
              text: this.$t('sys.button.submitSave') // 保存并提交
            },
            //    {
            //   compKey: 'btnKey3',
            //   type: '',
            //   size: 'small',
            //   icon: 'iconfont  icon-cancel',
            //   clickEvent: () => this.close(),
            //   text: this.$t('sys.button.delete') // 删除
            // },
            {
              compKey: 'btnKey4',
              type: '',
              size: 'small',
              icon: 'iconfont   icon-reset',
              clickEvent: () => this.reset(),
              text: '重置' // 重置
            },
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: '',

              clickEvent: () => this.handFileListChange(),
              text: '附件上传',
              position: 'upload'
            }

            //    {
            //   compKey: 'filePath',
            //   labelName: '上传附件：',
            //   codeField: 'filePath',
            //   component: () => import('@/components/upload/up.vue'),
            //   isMust: true,
            //   isRequire: true,
            //   span: 6
            // }
          ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '索赔类型：',
              codeField: 'claimOrderType',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: orgApis.purchaseApplicationClaimClaimType
              },
              isRequire: true,
              type: 'dropdownList',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '申请单号：',
              codeField: 'claimOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              isRequire: false,
              disabled: true,
              span: 8
            },
            {
              compKey: 'compKey3',
              labelName: '联系人：',
              codeField: 'contactPerson',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMust: true,
              span: 8
            },
            // {
            //   compKey: 'compKey8',
            //   labelName: '关联单号：',
            //   codeField: 'purOrderCode',
            //   isRequire: true,
            //   component: () =>
            //     import('@/components/org/commonInput/searchInput'),
            //   type: 'inputText',
            //   isMust: true,
            //   disabled: false,
            //   span: 6,
            //   isInput: true,
            //
            //   emitCode: this.change
            //
            //   // getComponentCode: () => this.change()
            // },
            {
              compKey: 'inStoreCode',
              labelName: '关联单号：',
              codeField: 'inStoreCode',
              textField: 'inStoreCode',
              // otherField: 'dlrId',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              isMust: true,
              // disabled: true,
              customObj: { showType: '' },
              dataToObject: {
                hiddenBtns: true,
                // oFields: 'dlrCode,dlrShortName',
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [],
                tableCols: [
                  {
                    prop: 'inStoreCode',
                    label: '备件入库单编码'
                  },
                  {
                    prop: 'billTypeCn',
                    label: '单据类型'
                  },
                  {
                    prop: 'inStoreDate',
                    label: '入库日期'
                  },
                  {
                    prop: 'inStoreAmount',
                    label: '入库总金额'
                  }
                ],
                formField: { },
                returnField: {
                  prop: 'inStoreCode',
                  label: '备件入库单编码'
                },
                api: {
                  APIUrl: '/mp/e3sh/spareparts/purchase/claimApplyForService/findRelevanceCode.do'
                }
              },
              span: 8,
              // isRequire: true
            },
            {
              compKey: 'compKey4',
              labelName: '出库凭证：',
              codeField: 'outCertificate',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: false,
              span: 8
            },
            {
              compKey: 'compKey5',
              labelName: '联系方式：',
              codeField: 'contactNumber',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMust: true,
              disabled: false,
              validrule: {
                isPhone: true, maxlength: 11
              },
              span: 8
            },
            {
              compKey: 'compKey6',
              labelName: '责任方：',
              codeField: 'responsibleParty',
              component: () => import('@/components/org/commonSelect'),

              customObj: {
                api: orgApis.purchaseApplicationClaimResponsibleParty
              },
              type: 'dropdownList',
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey7',
              labelName: '索赔原因：',
              codeField: 'claimReason',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: false,
              span: 8
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'bigAreaId',
              label: '大区ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partNo',
              label: '备件编码'
            },
            {
              prop: 'partName',
              label: '备件名称'
            },

            {
              prop: 'oemOutQty',
              label: '总部出库数量'
            },
            {
              prop: 'dlrInQty',
              label: '网点入库数量'
            },
            {
              prop: 'claimQty',
              label: '索赔申请数量',
              isShowLabel: false,
              isComponent: true,
              comps: [
                {
                  compKey: 'audit',
                  codeField: 'claimQty',
                  component: () => import('@/components/org/commonInput')
                }
              ]
            },
            {
              prop: 'claimDReason',
              label: '索赔原因+',
              isShowLabel: false,
              isComponent: true,
              comps: [
                {
                  compKey: 'audit',
                  codeField: 'claimDReason',
                  component: () => import('@/components/org/commonInput')
                }
              ]
            },
            {
              prop: 'claimPrice',
              label: '索赔单价'
            },
            {
              prop: 'claimAmount',
              label: '索赔金额'
            }
          ],
      formField: {
        claimReason: '',
        claimOrderType: '',
        claimOrderCode: '',
        contactPerson: '',
        contactNumber: '',
        responsibleParty: '',
        // purOrderCode:'POC2020330001',
        inStoreCode: '',
        outCertificate: ''
      },

      // formField: this.$utils.getFormField(
      //     this,
      //     {
      //     claimReason:'',
      //     claimOrderType:'',
      //     claimOrderCode:'',
      //     contactPerson:'',
      //     contactNumber:'',
      //     responsibleParty:'',
      //     purOrderCode:'POC2020330001',
      //     outCertificate:'',

      //       updateControlId: "",

      //     },
      //     this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      //   ),

      callbackObj: {
        // 手动勾选时
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection
          console.log(selection)
        },
        onCheckSelectChange: (selection) => {
          this.selectiondata = selection
          console.log(selection)
        }
      }
    }
  },
  watch: {
    'formField.inStoreCode': {
      deep: true,
      handler: function(newV, oldV) {
        console.log('watch中：', newV)
        // this.querybystatus(newV)
        // this.queryTable();
        if (!newV) {
          this.$refs['multipleTable'].list = []
          return
        }
        if (this.popupsState == 'edit') {
          this.search(
            orgApis.purchaseApplicationClaimMakeQuery,
            this.formField.inStoreCode
          )
        } else {
          this.search(
            orgApis.purchaseApplicationClaimMakeQueryAdd,
            this.formField.inStoreCode
          )
        }
      }
    },

    watchList: {

      deep: true,
      handler: function(newV, oldV) {
        const arr = this.$refs['multipleTable'].list

        console.log(newV)
        for (let i = 0; i < arr.length; i++) {
          arr[i].claimAmount = Number(arr[i].claimQty) * Number(arr[i].claimPrice)

          if (Number(arr[i].claimQty) > Number(arr[i].dlrInQty)) {
            console.log(arr[i].claimQty)
            console.log(arr[i].dlrInQty)
            this.$message.warning('索赔申请数量不能大于网点入库数量')
          }
        }
      }
      //  this.$refs["multipleTable"].list.forEach((item)=>{
      //    item.claimAmount = Number(item.claimQty) * Number(item.claimPrice)

      //   if(item.claimQty > item.dlrInQty){
      //     // item.claimQty = item.dlrInQty

      //     this.$message.warning('索赔申请数量不能大于网点入库数量')
      //     //  this.$set(item,'claimQty',item.dlrInQty)

      //   }
      // })

    }
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.queryform()
    // })
  },

  methods: {
    // 重置
    reset() {
      this.formField.claimReason = ''
      this.formField.claimOrderType = ''
      this.formField.claimOrderCode = ''
      this.formField.contactPerson = ''
      this.formField.contactNumber = ''
      this.formField.responsibleParty = ''
      this.formField.purOrderCode = ''
      this.formField.outCertificate = ''
    },

    // 保存并提交
    saveAndCommit() {
      this.$utils.validataMoth(this, 'validpage')
      if (!this.valid) return this.$message('校验未通过！')
      const arr = this.$refs['multipleTable'].list
      for (let i = 0; i < arr.length; i++) {
        if (Number(arr[i].claimQty) > Number(arr[i].dlrInQty)) {
          return this.$message.warning('索赔申请数量不能大于网点入库数量')
        }
      }

      this.saveOrCommit(
        orgApis.purchaseApplicationClaimTemporaryStorageSaveAndCommit
      )
    },

    showEdit() {
      this.editPopupsVisible = true
    },
    // 关闭弹窗
    closeEdit(type) {
      this.$emit('close', type)
    },
    // 弹框打开
    open() {
      if (this.popupsState == 'edit') {
        this.formField = this.editRowData
      }
    },

    change(e) {
      alert(e)
    },

    // 网格查询
    search(api, data) {
      const that = this
      // let obj = {
      //   data:data
      // }
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg /* 保存成功*/,
            type: 'success',
            duration: 1000
          })

          // that.$utils.deepCopy(that.$refs["multipleTable"].list) = response.rows
          //  this.$utils.deepCopy(this.$refs["multipleTable"].list) = response.rows

          this.$refs['multipleTable'].list = response.rows
          this.watchList = this.$refs['multipleTable'].list
          console.log(this.watchList)
        } else {
          // 保存失败
          this.$message({
            message: response.msg,
            type: 'warn',
            uration: 1000
          })
        }
      })
    },

    // 暂存
    TemporaryStorage() {
      const arr = this.$refs['multipleTable'].list
      console.log(arr)
      for (let i = 0; i < arr.length; i++) {
        if (Number(arr[i].claimQty) > Number(arr[i].dlrInQty)) {
          return this.$message.warning('索赔申请数量不能大于网点入库数量')
        }
      }

      this.saveOrCommit(orgApis.purchaseApplicationClaimTemporaryStorage)
    },

    saveOrCommit(api) {
      if (this.selectiondata.length < 1) { return this.$message('请至少勾选一条数据！') }
      const that = this
      this.formField.annex = this.uploadPath
      const obj = {

        ...this.formField,
        // associateOrderId: '0b9adc74-9139-11eb-af97-005056852a1a',
        claimOrderSubunitList: [...this.selectiondata],
        // upLoadList: this.upLoadList
        // upLoadList: this.uploadPath
      }
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: obj
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg /* 保存成功*/,
            type: 'success',
            duration: 1000
          })

          this.closeEdit()
          this.$parent.queryTable()

          // that.$utils.deepCopy(that.$refs["multipleTable"].list) = response.rows
          //  this.$utils.deepCopy(this.$refs["multipleTable"].list) = response.rows

          //  this.$refs["multipleTable"].list = response.rows
        } else {
          // 保存失败
          this.$message({
            message: response.msg,
            type: 'warn',
            uration: 1000
          })
        }
      })
    },

    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能上传后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const that = this
      const url = '/mp/file/notice/upload.do'
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '上传成功',
              type: 'success'
            })
            this.upLoadList = response.path
            const [name, path] = response.path[0][0].split('|')
            this.uploadPath = path
            // that.queryTable();
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch((err) => {})
    }
    // queryform() {
    // var queryid = { orderId: this.dataForForm.saleOrderId }
    // // 先读取参数中的传输对象
    // const returnObj = {
    // // api配置
    //   apiConfig: orgApis.orderinvoicedetailsQuery,
    // 条件/实体参数（变量），根据typeParam中的定义配置
    // variables: queryid
    // }
    // 转换了中台请求格式数据
    // var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
    // 调用中台API方法（可复用）
    // this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
    //   if (response.result === '0') {
    //     if (response.msg) {
    //       this.$message({
    //         message: response.msg,
    //         type: 'warn',
    //         uration: 2000
    //       })
    //     }
    //     return
    //   }
    //   // 返回json
    //   if (response.result === '1') {
    //     Object.assign(this.formField, response.rows[0], response.rows[1])
    //     console.log(this.formField)
    //   }
    // }).catch(err => {
    //   console.info(err)
    // })
    // }
  }
}
</script>
<style lang='scss' scoped>
/deep/ .el-dialog {
  margin-top: 5rem !important;
}
</style>
